<template>
  <div>
    <a-select
      :value="val"
      show-search
      placeholder="请选择"
      style="width: 100%"
      :filter-option="false"
      :not-found-content="fetching ? undefined : '未查询到内容'"
      @search="fetchUser"
      @change="handleChange"
    >
      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
      <a-select-option
        v-for="d in data"
        :key="d.supplierCode"
        :value="d.supplierName"
      >
        {{ d.supplierName }}
      </a-select-option>
    </a-select>
  </div>
</template>
<script>
import debounce from 'lodash/debounce'

export default {
  props: {
    value: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    this.fetchUser = debounce(this.fetchUser, 800)
    return {
      data: [this.value],
      val: this.value,
      fetching: false
    }
  },
  mounted() {
    this.fetchUser()
  },
  methods: {
    fetchUser(value = '') {
      this.fetching = true

      this.$api.plan
        .fetchList('/doc/list-supplier', {
          supplierName: value,
          pageNum: 1,
          pageSize: 102
        })
        .then(res => {
          this.fetching = false
          this.data = []
          this.data = [
            ...Array.from(
              new Set(
                res.map(_ => {
                  return {
                    supplierName: _.supplierName,
                    supplierCode: _.supplierCode,
                    id: _.id
                  }
                })
              )
            )
          ]
        })
    },
    handleChange(value) {
      this.val = value
      this.$emit('input', value)
      Object.assign(this, {
        data: [],
        fetching: false
      })
    }
  }
}
</script>
